import Vue from 'vue';
import axios from 'axios';
import env from '../../build/env';
import iView from 'iview';
import {router} from '../router/index';
import store from '../store/index';
import Cookies from 'js-cookie';
Vue.use(iView);
//权限管理系统
export const adminUrl=env === 'production' ? 'https://www.url.com' : '';
//加盟商管理系统
export const jmsUrl=env === 'production' ? 'https://www.url.com' : '';

var instance = axios.create({
  timeout: 50000
});
//axios 响应拦截
instance.interceptors.response.use(function (response) {
  return response;
}, function (error) {
  if(error.response.status==404){//找不到数据接口
    router.push({name:"error-404"});
  }
  if(error.response.status==500){//服务器错误
    router.push({name:"error-500"});
  }
  if(error.response.status==403){//暂无操作权限
    router.push({name:"error-403"});
  }
  if(error.response.status==401){//token过期
    new Vue().$Message.warning({
      content:'会话过期，请重新登录',
      duration:2,
      onClose:function () {
        Cookies.remove('user');
        let themeLink = document.querySelector('link[name="theme"]');
        themeLink.setAttribute('href', '');
        let theme = '';
        if (localStorage.theme) {
          theme = localStorage.theme;
        }
        localStorage.clear();
        sessionStorage.clear();
        if (theme) {
          localStorage.theme = theme;
        }
        store.commit('clearOpenedSubmenu');
        router.push({name:'login'})
      }
    })
  }
  return Promise.reject(error);
});
//axios中的get请求
export function fetchGetData(url,params) {
  setToken();
  return new Promise((resolve, reject)=>{
    instance.get(url,{params:params})
      .then(function(res){
        if (res.status >= 200 && res.status < 300) {
          return resolve(res.data)
        }else {
          return reject(new Error(res.status))
        }
      })
      .catch(function(err){
        console.log(err);
      });
  });
};
//axios中的post请求
export function fetchPostData(url,params){
  setToken();
  iView.LoadingBar.start();
  return new Promise((resolve, reject)=>{
    instance.post(url,params)
      .then(function(res){
        iView.LoadingBar.finish();
        if (res.status >= 200 && res.status < 300) {
          return resolve(res.data)
        }else {
          return reject(new Error(res.status))
        }
      })
      .catch(function(err){
        console.log(err);
      });
  });
}

function setToken() {
  var tokenVal = sessionStorage.getItem("token");
  if(tokenVal) {
    instance.defaults.headers.common['x-token']=tokenVal;
  }
}